<?php

namespace app\api\controller\v1\pink;

use app\Request;
use app\services\activity\StorePinkServices;
use app\services\product\product\StoreProductServices;
use app\services\user\UserServices;
use think\facade\Db;

class StorePinkController
{
    /**
     * @param int $pink_type
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function pinkList(Request $request, int $pink_type)
    {
        /** @var StoreProductServices $storeProductServices */
        $storeProductServices = app()->make(StoreProductServices::class);
        /** @var StorePinkServices $storePinkServices */
        $storePinkServices = app()->make(StorePinkServices::class);
        $pinkList = $storePinkServices->pinkList($pink_type, $request->uid());
        $setting = Db::table('eb_combination_setting')->select()->toArray();
        $config = [];
        foreach($setting as $value){
            $config[$value['name']] = $value['value'];
        }
        foreach ($pinkList as &$pink) {
            $pink['rebate'] = round($pink['total_price'] * $config["pink{$pink['people']}_rebate"] / 100, 2);
            $pink['product'] = $storeProductServices->getOne(['id' => intval($pink['cid'])]);
        }

        //处理拼团到结束时间还未成团任务
        $storePinkServices->_handleOverPinkList();
        return app('json')->successful('ok', ['pinkList' => $pinkList]);
    }

    public function pinkListByUid(Request $request)
    {
        /** @var StoreProductServices $storeProductServices */
        $storeProductServices = app()->make(StoreProductServices::class);
        /** @var StorePinkServices $storePinkServices */
        $storePinkServices = app()->make(StorePinkServices::class);
        $pinkList = $storePinkServices->pinkListByUid(intval($request->uid()));
        $winners = $storePinkServices->pinkWinList(array_column($pinkList, 'id'));
        $winUsers = [];
        foreach ($winners as $winner) {
            $winUsers[$winner['pid']] = $winner['nickname']??'';
        }
        $setting = Db::table('eb_combination_setting')->select()->toArray();
        $config = [];

        foreach($setting as $value){
            $config[$value['name']] = $value['value'];
        }
        foreach ($pinkList as &$pink) {
            $pink['winner'] = empty($winUsers[$pink['id']]) ? '' : $winUsers[$pink['id']];
            $pink['rebate'] = round($pink['total_price'] * $config["pink{$pink['people']}_rebate"] / 100, 2);
            $pink['product'] = $storeProductServices->getOne(['id' => intval($pink['cid'])]);
        }
        return app('json')->successful('ok', ['pinkList' => $pinkList]);
    }

    public function pinkJoinListByUid(Request $request)
    {
        /** @var StoreProductServices $storeProductServices */
        $storeProductServices = app()->make(StoreProductServices::class);
        /** @var StorePinkServices $storePinkServices */
        $storePinkServices = app()->make(StorePinkServices::class);
        $pinkList = $storePinkServices->pinkJoinListByUid(intval($request->uid()));
        $setting = Db::table('eb_combination_setting')->select()->toArray();
        $config = [];
        foreach($setting as $value){
            $config[$value['name']] = $value['value'];
        }
        foreach ($pinkList as &$pink) {
            $pink['rebate'] = round($pink['total_price'] * $config["pink{$pink['people']}_rebate"] / 100, 2);
            $pink['product'] = $storeProductServices->getOne(['id' => intval($pink['cid'])]);
        }
        return app('json')->successful('ok', ['pinkList' => $pinkList]);
    }

    public function search(Request $request)
    {
        $get = $request->getMore([
            ['keyword', ''],
            ['page', 1],
            ['limit', 8],
        ]);
        /** @var StoreProductServices $storeProductServices */
        $userServices = app()->make(UserServices::class);
        $leader = $userServices->getUidByKeyword($get['keyword']);
        /** @var StoreProductServices $storeProductServices */
        $storeProductServices = app()->make(StoreProductServices::class);
        /** @var StorePinkServices $storePinkServices */
        $storePinkServices = app()->make(StorePinkServices::class);
        $pinkList = $storePinkServices->pinkListByUid(intval($leader['uid']));
        $setting = Db::table('eb_combination_setting')->select()->toArray();
        $config = [];
        foreach($setting as $value){
            $config[$value['name']] = $value['value'];
        }
        foreach ($pinkList as &$pink) {
            $pink['rebate'] = round($pink['total_price'] * $config["pink{$pink['people']}_rebate"] / 100, 2);
            $pink['product'] = $storeProductServices->getOne(['id' => intval($pink['cid'])]);
        }
        return app('json')->successful('ok', ['pinkList' => $pinkList]);
    }

    /**
     * 发起拼团
     * @param Request $request
     * @return mixed
     */
    public function create(Request $request)
    {
        if (time() >= strtotime(date('Y-m-d 21:00:00'))) {
            return app('json')->fail('平台拼团时间10:00 ~ 20:59，明天记得准时来拼哟!');
        }
        if (time() < strtotime(date('Y-m-d 10:00:00'))) {
            return app('json')->fail('平台拼团时间10:00 ~ 21:59，明天记得准时来拼哟!');
        }
        $uid = intval($request->uid());
        $post = $request->postMore([
            ['cid', 0],   // 拼团商品ID
            ['total_num', 1],   // 拼团商品ID
        ]);

        /** @var StoreProductServices $storeProductServices */
        $storeProductServices = app()->make(StoreProductServices::class);
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        /** @var StorePinkServices $storePinkServices */
        $storePinkServices = app()->make(StorePinkServices::class);
        if ($storePinkServices->lunchCount($uid) >= 1) {
            return app('json')->fail('您的上一个团还未完成，完成该团后才能继续发团!');
        }

        $product = $storeProductServices->getOne(['id' => intval($post['cid'])]);
        if (intval($product->stock) <= 0) {
            return app('json')->fail('该商品库存不足!');
        }
        $userStartNum = $userServices->startNum($uid);
        $totalStartNum = $product->product_start_num * intval($post['total_num']);
        if ($totalStartNum > $userStartNum) {
            return app('json')->fail('您的发团点不足!');
        }

        if ($pink = $storePinkServices->launchPink($uid, $totalStartNum, $post['total_num'], $product)) {
            $storeProductServices->decProductStock(1, intval($post['cid']));
            return app('json')->successful('ok', ['pink' => $pink]);
        }
        return app('json')->fail('发团失败!');
    }

    public function detail(int $tid)
    {
        /** @var StorePinkServices $storePinkServices */
        $storePinkServices = app()->make(StorePinkServices::class);
        $detail = $storePinkServices->getPinkDetail((int)$tid);
        if ($detail['pid'] > 0) {
            return app('json')->fail('无此拼团!');
        }
        $detail['currentTime'] = time();
        return app('json')->successful('ok', compact('detail'));
    }

//    public function join(Request $request)
//    {
//        $post = $request->postMore([
//            ['pink_type', 4],
//            ['pink_id', 0],
//        ]);
//        $uid = intval($request->uid());
//        /** @var StoreProductServices $storeProductServices */
//        $storeProductServices = app()->make(StoreProductServices::class);
//        /** @var UserServices $userServices */
//        $userServices = app()->make(UserServices::class);
//        /** @var StorePinkServices $storePinkServices */
//        $storePinkServices = app()->make(StorePinkServices::class);
//        $topPink = $storePinkServices->getOne(['id' => intval($post['pink_id'])]);
//
//        if ($storePinkServices->getOne(['pid' => intval($post['pink_id']), 'uid' => $uid])) {
//            return app('json')->fail('请勿重复参团!');
//        }
//        if (time() > intval($topPink['stop_time'])) {
//            return app('json')->fail('该团已超时关闭!');
//        }
//        if (intval($topPink['people']) <= intval($topPink['pink_people'])) {
//            return app('json')->fail('该团已满!');
//        }
//        $inc = $storePinkServices->incPinkPeople(intval($post['pink_id']), 'pink_people');
//        if ($inc) {
//            // TODO: 支付
//            if ($join = $storePinkServices->joinPink($uid, $topPink)) {
//                $top = $storePinkServices->getOne(['id' => intval($post['pink_id'])]);
//                if ($top['pink_people'] >= $top['people']) {
//                    $top->status = 2;
//                    $top->save();
//                    $win = rand(2, intval($topPink['people']));
//                    $winner = $storePinkServices->openPink($win, intval($post['pink_id']));
//                    // TODO: 加入订单
//                    var_dump($winner);die();
//                }
//                return app('json')->successful('ok', compact('join'));
//            }
//            $storePinkServices->decPinkPeople(intval($post['pink_id']), 'pink_people');
//        }
//        return app('json')->fail('参团失败!');
//    }

}